package com.wxy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxy.entity.Saledata;
import com.wxy.entity.Saledetaildata;
import com.wxy.mapper.SaledataMapper;
import com.wxy.selectUser.SelectUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.sql.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wxy
 * @since 2022-01-12
 */
@RestController
@RequestMapping("/saleData")
public class SaledataController {

    @Autowired
    private SaledataMapper saledataMapper;

    //按日账单查询
    @GetMapping("/getDayData/{page}")
    public IPage getDayData(
            HttpServletRequest request,
            @PathVariable("page") Integer pageNum
    ){
        //取出page
        QueryWrapper qw =  SelectUser.saleDayDataSelectUser(request.getHeader("userId"));
        qw.orderByDesc("time");
        IPage page = new Page(pageNum,10);
        return saledataMapper.selectPage(page,qw);
    }


    //按日期查询日账单getDayDateByTime
    @GetMapping("/getDayDataByTime/{time}")
    public List getDayDataByTime(
            HttpServletRequest request,
            @PathVariable("time") Date time
    ){
        //取出page
        QueryWrapper qw =  SelectUser.saleDataSelectUser(request.getHeader("userId"));
        qw.eq("time",time);
        return saledataMapper.selectList(qw);
    }

    //日数据更新
    @PostMapping("/updateDayData")
    public Boolean updateDayData(
            @RequestBody Saledata saledata
    ){
        saledataMapper.updateById(saledata);
        return true;
    }
    //单日数据插入
    @PostMapping("/insertDayData")
    public Boolean insertDayData(
            @RequestBody Saledata saledata,
            HttpServletRequest request
    ){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("id");
        queryWrapper.last("limit 1");
        //查到上一条数据
        Saledata lastOne =  saledataMapper.selectOne(queryWrapper);
        //自动生成今天的数据
        saledata.setUserId(Integer.valueOf(request.getHeader("userId").toString()));
        Integer profit = saledata.getProjectIncome()- saledata.getProjectCost();
        String growth = String.valueOf(profit-lastOne.getProjectProfit().intValue());
        saledata.setGrowth(growth);
        saledata.setProjectProfit(profit);
        saledataMapper.insert(saledata);
        return true;
    }


}

